# -*- coding: utf-8 -*-
from django.http import HttpResponse

from django.template.loader import get_template
from django.template import Context

from django.db import connection
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson

from django.core.context_processors import csrf
from django.http import QueryDict

import types     

class PostRequests:
    def checkItem(self, item, handler):
        if types.ListType == type(item):
            for i in item:
                self.checkItem(i, handler);
        elif types.DictType == type(item):
            self.checkItem(item.keys(), handler);
        else:
            print 'PostRequests.checkItem: item=', item, type(item)
            json = simplejson.loads(item)
            if(json.has_key('data_container')):
                data = json.get('data_container')
                print 'PostRequests.checkItem: json data=', data
                if types.ListType == type(data):
                    for i in data:
                        try:
                            handler(i);
                        except e:
                            print 'PostRequests.checkItem: handler exception 1'
                else:
                    try:
                        handler(data);
                    except e:
                        print 'PostRequests.checkItem: handler exception 2'
    def receive(self, request, handler):
        post = request.POST.dict();
        print 'post=', post
        return self.checkItem(post, handler)

    def send(self, data = []):
        result = simplejson.dumps(data, cls=DjangoJSONEncoder)
        return HttpResponse(result, mimetype='application/json');

        
